package com.example.permission.myjbm.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.activity.LoginActivity;
import com.example.jbmsuppliers.sinopec.orderaddress.MyAddRessRepair;
import com.example.permission.myjbm.config.Config;
import com.example.permission.myjbm.fragments.MyFragment;
import com.example.permission.myjbm.utils.ImageLoaderInit;
import com.example.permission.myjbm.utils.LoginSharedPreferences;
import com.example.permission.myjbm.view.MeauseGridView;
import com.example.weather.smoothImage.ImagePagerActivity;
import com.jbm.jbmsupplier.util.InfomationEntity;
import com.jbm.jbmsupplier.util.enums.PraiseType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.jbm.jbmsupplier.util.abstracts.SendMessageInterfase.gSocket;

/**
 * 首页面适配器
 * 朋友圈的适配器   与MyFragment相关联
 */

public class MyFragmentAdapter extends BaseAdapter {

//    private final MyPopupWindow popup;
    private  LoginSharedPreferences sp;
    private ArrayList<InfomationEntity> arr1;
    private Context c;
    private MeauseGridView gv;
    private ArrayList<String> picArr;
    private   SimpleDateFormat df;
    private boolean isNet;


    public MyFragmentAdapter(List<InfomationEntity> arr, Context c, boolean isNet){
        arr1= (ArrayList<InfomationEntity>) arr;
        this.isNet=isNet;
        this.c=c;
        picArr=new ArrayList<String>();
        if (sp==null){
        sp=new LoginSharedPreferences(c);}
        this.df = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

//       popup= MyPopupWindow.getInstance(c, new MyPopupWindow.DianZan() {
//            @Override
//            public void pingLun() {
//
//            }
//            @Override
//            public void dianZan() {
//
//            }
//        });

    }

    //更新数据
    public void setNotify(List<InfomationEntity> arr){

        arr1= (ArrayList<InfomationEntity>) arr;
        notifyDataSetChanged();

    }

    @Override
    public int getCount() {
        return arr1.size();
    }

    @Override
    public Object getItem(int position) {
        return arr1.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
         MyHolder holder=null;
                if(convertView==null){
                    convertView =View.inflate(c, R.layout.adapter_item1,null);
                    holder=new MyHolder(convertView);
                    convertView.setTag(holder);
                }else{
                    holder= (MyHolder) convertView.getTag();
                }
                initView(arr1.get(position),position,holder);
        return convertView;
    }
//初始化数据
    private void initView(InfomationEntity infomationEntity,int position ,MyHolder holder) {
        contentDispose(infomationEntity,position,holder);
      //设置时间
        holder. item_date.setText(infomationEntity.getDealtime().equals("0")?df.format(infomationEntity.getUpdateDate()):infomationEntity.getDealtime());
       if(infomationEntity.getUserinfo()!=null){
           holder.item_user_name.setText(infomationEntity.getUserinfo().getNickname());
           if(infomationEntity.getUserinfo().getLogo().length()<5){
               holder.item_user_img.setImageResource(R.mipmap.pic);
           }else {
               ImageLoaderInit.getInstance().photoShow(infomationEntity.getUserinfo().getLogo(), holder.item_user_img);
           }
       }
        pictureBrowse(infomationEntity,holder,position);
        bounced(holder,infomationEntity,position);
    }





    //用来记录当前点击的位置  服务器回调用
    private int currentIndex;
    /**
     * 弹出关注和点赞
     * @param holder
     */
    private void bounced(final MyHolder holder, final InfomationEntity infomationEntity, final int possition) {
//        holder.item_showmessage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popup .show(v,  150, 90);
//            }
//        });
//
//        holder.big.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                popup.hidden();
//                return false;
//            }
//        });
    //初始化是否收藏
        holder.item_isCollect.setText(infomationEntity.getFocusCount()+"");
        holder.item_isAttention.setText(infomationEntity.getPraiseCount()+"");
        if(infomationEntity.isCollect()){

            holder.item_isCollect.setChecked(true);
        }else{
            holder.item_isCollect.setChecked(false);
        }
        //初始化是否点赞
        if(infomationEntity.isAttention()){

            holder.item_isAttention.setChecked(true);
        }else{
            holder.item_isAttention.setChecked(false);
        }


        //收藏
        holder.item_isCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sp.getLoginState()!= true){
                    holder.item_isCollect.setChecked(false);
                    c.startActivity(new Intent(c, LoginActivity.class));
                    return ;
                }

                if(isNet==true){
                    if(infomationEntity.isCollect()){
                        holder.item_isCollect.setChecked(true);
                    }else{
                        holder.item_isCollect.setChecked(false);
                    }
                    return ;
                }


                if(infomationEntity.isCollect()==true){
                    holder.item_isCollect.setChecked(true);
                    Toast.makeText(c, "您已收藏", Toast.LENGTH_SHORT).show();
                    return ;
                }
                if(infomationEntity.isCollect()==false){
                    //收藏接口
                    option.shoucang(infomationEntity.getInfoId(),gSocket.login_id, PraiseType.info.toValue());
                    currentIndex=possition;
                }else{
                    holder.item_isCollect.setChecked(false);
                    infomationEntity.setCollect(false);
                }
            }
        });
        //点赞
        holder.item_isAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sp.getLoginState()!= true){
                    holder.item_isAttention.setChecked(false);
                    c.startActivity(new Intent(c, LoginActivity.class));
                    return;
                }


                if(isNet==true){
                    if(infomationEntity.isAttention()){
                        holder.item_isAttention.setChecked(true);
                    }else{
                        holder.item_isAttention.setChecked(false);
                    }

                    return ;
                }



                holder.item_isAttention.setChecked(false);
                if(infomationEntity.isAttention()==true){
                    holder.item_isAttention.setChecked(true);
                    Toast.makeText(c, "您已点赞", Toast.LENGTH_SHORT).show();
                    return ;
                }
                if(infomationEntity.isAttention()==false){
                    //调用点赞接口
                    option.dianzan(infomationEntity.getInfoId(),gSocket.login_id, PraiseType.info.toValue());
                    currentIndex=possition;
                }else{
                    holder.item_isAttention.setChecked(false);
                    infomationEntity.setAttention(false);
                }
            }
        });
    }
        //服务器返回
    public void netBack(boolean isSuccess,String flag){
            if(isSuccess==true){
                //收藏
                InfomationEntity infomationEntity = arr1.get(currentIndex);
                if(flag.equals("shoucang")){
                    Toast.makeText(c, "收藏成功", Toast.LENGTH_SHORT).show();
                    infomationEntity.setFocusCount(infomationEntity.getFocusCount()+1);
                    infomationEntity .setCollect(true);
                //点赞
                }else if(flag.equals("dianzan")){
                    Toast.makeText(c, "点赞成功", Toast.LENGTH_SHORT).show();
                    infomationEntity.setPraiseCount(infomationEntity.getPraiseCount()+1);
                    infomationEntity.setAttention(true);
                }
            }
        notifyDataSetChanged();

    }


    //  public int cout;
    /**
     * 处理内容   收缩及显示
     *
     */
    private void contentDispose(final InfomationEntity infomationEntity, final int position, final MyHolder holder) {
        //    dian.init(holder.item_isShow, position,holder.item_isShow);
     //   holder.item_isShow.setVisibility(View.GONE);

        //设置内容
        if(infomationEntity.getContent().length()<1){
            holder.item_content.setVisibility(View.GONE);
        }else {
            holder.item_content.setVisibility(View.VISIBLE);
            holder.item_content.setText(infomationEntity.getContent());
        }

        holder.item_isShow.setVisibility(View.GONE);
        //获取行高
        holder.item_content.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {

                holder.item_content.getViewTreeObserver().removeOnPreDrawListener(this);
                int cout = holder.item_content.getLineCount();
                infomationEntity.setMaxnum(cout);
              //  holder.item_content.setTag((int)holder.item_content.getLineCount());
                if (cout > 2) {
                    holder.item_isShow.setVisibility(View.VISIBLE);
                } else {
                    holder.item_isShow.setVisibility(View.GONE);
                }
                return true;
            }
        });
        if(infomationEntity.getIsShow()==0){
            holder.item_content.setMaxLines(2);
            holder.item_isShow.setText("全文");
        }else{
            holder.item_content.setMaxLines(infomationEntity.getMaxnum());
            holder.item_isShow.setText("收起");
        }

        holder.item_isShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (infomationEntity.getIsShow()==0) {
                    holder.item_content.setMaxLines(infomationEntity.getMaxnum());
                    infomationEntity.setIsShow(1);
                    holder.item_isShow.setText("收起");
                } else {
                    holder.item_content.setMaxLines(2);
                    infomationEntity.setIsShow(0);
                    holder.item_isShow.setText("全文");

                }
                holder.item_content.setText(arr1.get(position).getContent());
            }
        });

    }

    //浏览图片
    private void pictureBrowse(final InfomationEntity infomationEntity, MyHolder holder, final int position1) {
        holder.item_photo_video.removeAllViews();
        if(infomationEntity.getAttList().size()!=0){
            holder.item_photo_video.setVisibility(View.VISIBLE);
        gv=new MeauseGridView(c);
        gv.setAdapter(new MyFragmentAdapter_gv(infomationEntity.getAttList(),c));
        holder.item_photo_video.addView(gv);
                gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if(MyFragment.flag==0){
                        if(position1==0){
                            if (sp.getLoginState() != true) {
                                c.startActivity(new Intent(c, LoginActivity.class));
                                return;
                            }
                            c.startActivity(new Intent(c, MyAddRessRepair.class));
                            return;
                        }
                        }
                        picArr.clear();
                        for(int i=0;i<infomationEntity.getAttList().size();i++){//infomationEntity.getAttList().size()
                            picArr.add(Config.PHOTOPATH+infomationEntity.getAttList().get(i).getAttPath());
                        }

                        Intent intent = new Intent(c, ImagePagerActivity.class);
                        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
                        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, picArr);
                        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                        c.startActivity(intent);
                    }
                });


        }
    }
    //点赞 和 收藏调用的接口
   private RequestOption option;
    public void setRequestOption(RequestOption option){
        this.option=option;
    }
    public interface RequestOption{
        void dianzan(int infoid, int loginid, int praiseType);
        void shoucang(int infoid, int loginid, int praiseType);
    }



    public class MyHolder{
        private final ImageView item_user_img;

        private final TextView item_user_name,item_date;
        public final TextView item_content,item_isShow;
        private final LinearLayout item_photo_video,big;
        private final CheckBox item_isCollect,item_isAttention;

        public MyHolder(View convertView){
            //用户头像
            item_user_img=(ImageView)convertView.findViewById(R.id.item_user_img);
            //用户名称
            item_user_name=(TextView)convertView.findViewById(R.id.item_user_name);
            //用户发送的文字
            item_content=(TextView)convertView.findViewById(R.id.item_content);
            //收起和显示全部
            item_isShow=(TextView)convertView.findViewById(R.id.item_isShow);
            //是图片还是添加视频
            item_photo_video=(LinearLayout)convertView.findViewById(R.id.item_photo_video);
            //弹出点赞和关注
          //  item_showmessage=(ImageView)convertView.findViewById(R.id.item_showmessage);
            //收藏
            item_isCollect=(CheckBox)convertView.findViewById(R.id.item_isCollect);
            //点赞
            item_isAttention=(CheckBox)convertView.findViewById(R.id.item_isAttention);
            //最外层的
            big=(LinearLayout)convertView.findViewById(R.id.big);
            //时间
            item_date=(TextView)convertView.findViewById(R.id.item_date);
        }
    }

}
